// pages/homePage/homePage.js
const app = getApp();
const {
  total_standards_child,
  total_standards_young,
  total_standards_adult,
  start_standards_child,
  start_standards_young,
  start_standards_adult,
  wake_standards,
  deep_standards_child,
  deep_standards_young,
  deep_standards_adult,
  heartRate_standards,
  step_standards_child,
  step_standards_young,
  step_standards_adult
} = require("../../../utils/standards-score.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    weekDay: '',
    end: "",
    now: "",
    healthScore: "无",
    sleepScore: "无数据",
    heartRateScore: "无数据",
    testLevel: "暂无",
    stepScore: "无数据",
    elec: "暂无",
    age: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    let now = new Date(new Date().getTime() - 24 * 60 * 60 * 1000).format("yyyy/MM/dd");
    let weekday = app.utils.formatWeekday(new Date(now).getDay());

    that.setData({
      weekDay: weekday,
      now: now,
      end: now
    })
    wx.getStorage({
      key: 'openId',
      success: function(res) {
        that.getStuAndParInfoByOpenId(res.data);
      }
    })
  },
  //获取学生和家长的信息
  getStuAndParInfoByOpenId(openId) {
    let that = this;
    app.api.ajaxSubmit("/node/wx/tools/getStuAndParInfoByOpenId", {
      openId: openId
    }).then(response => {
      let info = response.data.data;
      if (response.data.error == 10000 && info) {
        app.globalData.student = {
          ...info.studentInfo,
          grade: info.grade,
          classId: info.classId,
          schoolId: info.schoolId
        };
        wx.setStorageSync("student", {
          ...info.studentInfo,
          grade: info.grade,
          classId: info.classId,
          schoolId: info.schoolId
        });
        wx.setStorageSync("parent", info.parentInfo);
        wx.setStorageSync("parents", info.parents);
        wx.setStorageSync("height", info.height);
        wx.setStorageSync("weight", info.weight);
        let age = new Date().getFullYear() - new Date(info.studentInfo.birthday).getFullYear();
        that.setData({
          age: age
        })

        that.getDeviceNumByStuId(info.studentInfo.studentId);

      }
    }).catch(err => {
      wx.showToast({
        title: '服务器开小差',
        icon: "none",
        duration: 2000
      })
    })
  },
  //根据学生id获取绑定手环
  getDeviceNumByStuId(stuId) {
    let that = this;
    app.api.ajaxSubmit("/node/wx/home/getDeviceNumByStuId", {
      studentId: stuId
    }).then(response => {
      if (response.data.error == 10000 && response.data.data) {
        wx.setStorageSync("deviceNum", response.data.data.deviceNum);
        that.getHealthData(wx.getStorageSync("student").studentNumber);
        that.getVoltage();
      }
    })

  },
  circleCanves(id, ringWidth, radius, position1, position2, x, y) {
    var cxt_arc = wx.createCanvasContext(id);
    var gr = cxt_arc.createLinearGradient(0, 100, 100);
    gr.addColorStop(0, '#91D5FF');
    gr.addColorStop(1, '#40A9FF');
    cxt_arc.setLineWidth(ringWidth);
    cxt_arc.setStrokeStyle('#d2d2d2');
    cxt_arc.setLineCap('round')
    cxt_arc.beginPath(); //开始一个新的路径
    cxt_arc.arc(x, y, radius, Math.PI * 3 / 4, Math.PI * 1 / 4, false);
    //设置原点(80,80)，半径为50的圆的路径到当前路径
    cxt_arc.stroke(); //对当前路径进行描边

    cxt_arc.setLineWidth(ringWidth);
    cxt_arc.strokeStyle = gr;
    cxt_arc.setLineCap('round')
    cxt_arc.beginPath(); //开始一个新的路径
    cxt_arc.arc(x, y, radius, Math.PI * position1, Math.PI * position2, false);
    cxt_arc.stroke(); //对当前路径进行描边

    cxt_arc.draw();
  },
  bindDateChange(e) {
    let weekday = app.utils.formatWeekday(new Date(e.detail.value).getDay())

    this.setData({
      now: e.detail.value.replace(/-/g, "/"),
      weekDay: weekday
    })

    this.getHealthData(wx.getStorageSync("student").studentNumber);
  },
  toHealthPage() {
    if (this.data.healthScore == "无") return;
    wx.navigateTo({
      url: '/pages/homePage/health/health',
    })
  },
  toSleepPage() {
    if (this.data.sleepScore == "无数据") return;
    wx.navigateTo({
      url: '/pages/homePage/sleep/sleep',
    })
  },
  toHeartpPage() {
    if (this.data.heartRateScore == "无数据") return;
    wx.navigateTo({
      url: '/pages/homePage/heartRate/heartRate',
    })
  },
  toStepPage() {
    if (this.data.stepScore == "无数据") return;
    wx.navigateTo({
      url: '/pages/homePage/step/step',
    })
  },
  //获取健康数据
  getHealthData(studentNumber) {
    let that = this;
    app.api.ajaxSubmit("/node/wx/home/getHealthData", {
      studentNumber: studentNumber,
      deviceNum: wx.getStorageSync("deviceNum"),
      date: that.data.now
    }).then(response => {
      let info = response.data.data;
      if (response.data.error == 10000 && info) {
        that.dataHandle(info);
      }
    }).catch(err => {
      wx.showToast({
        title: '服务器开小差',
        icon: "none",
        duration: 2000
      })
    })
  },
  //数据处理
  dataHandle(data) {
    let braceleInfo = data.braceleInfo;
    let option = new Map([
      [1, "优秀"],
      [2, "良好"],
      [3, "及格"],
      [4, "不及格"],
      [-99999, "暂无"]
    ]);
    let testInfo = data.testInfo;
    let arr = Object.keys(testInfo);
    let testScore = arr.length ? testInfo.score / 100 : 0;
    let testLevel = arr.length ? testInfo.level : -99999;

    let sleepScore = data.stepPass == 2 ? 0 : this.getSleepScore(braceleInfo.sleepData);
    let keysArr = Object.keys(braceleInfo.heartRateData);
    let heartRate = data.heartRatePass == 2 || !keysArr.length ? 0 : braceleInfo.heartRateData.averageHeartRate;
    let heartRateScore = this.calcHeartScore(heartRate);
    let stepNum = data.stepPass == 2 ? 0 : braceleInfo.stepData;
    let setpScore = this.calcStepScore(stepNum);

    let healthScore = this.calcHealthScore(testScore, sleepScore, heartRateScore, setpScore);

    let width = wx.getSystemInfoSync().windowWidth;
    let ringWidth = width / 375 * 10;
    let radius = width / 375 * 80;
    let x = ringWidth + radius;

    this.circleCanves('canvasArc', ringWidth, radius, 3 / 4, 0.75 + 1.5 * (healthScore / 100), x, x);

    this.setData({
      healthScore: healthScore ? healthScore : "无",
      sleepScore: sleepScore ? sleepScore + "分" : "无数据",
      heartRateScore: heartRate ? heartRate + "次/分" : "无数据",
      testLevel: option.get(testLevel),
      stepScore: stepNum ? stepNum + "步" : "无数据",
    })
  },
  //计算睡眠得分
  getSleepScore(option) {
    let sleepLengthScore, sleepStartScore, wakeupScore, depthScore;
    let sleepTotal = option.sleepTotal / 3600;
    let sleepStart = new Date(option.sleepStartTime).getHours();
    // sleepStart = sleepStart < 12 ? (24 + sleepStart) : sleepStart;
    let wakeUpCount = option.wakeUpCountl;
    let depthPercent = option.depthPercent;
    if (sleepTotal == 0 || !option.sleepTotal) return 0;

    let total_standards, start_standards, deep_standards, rate = [];
    if (this.data.age < 13 && this.data.age >= 6) {
      total_standards = total_standards_child;
      start_standards = start_standards_child;
      deep_standards = deep_standards_child;
      rate = [0.4, 0.2, 0.15, 0.25];
    } else if (this.data.age < 17 && this.data.age >= 14) {
      total_standards = total_standards_young;
      start_standards = start_standards_young;
      deep_standards = deep_standards_young;
      rate = [0.35, 0.25, 0.15, 0.25];
    } else {
      total_standards = total_standards_adult;
      start_standards = start_standards_adult;
      deep_standards = deep_standards_adult;
      rate = [0.35, 0.3, 0.15, 0.2];
    }

    total_standards.some(item => {
      if (item.begin <= sleepTotal && sleepTotal < item.end) {
        sleepLengthScore = item.score;
        return true;
      }
    })

    start_standards.some(item => {
      if (item.begin <= sleepStart && sleepStart < item.end) {
        sleepStartScore = item.score;
        return true;
      }
    })

    wake_standards.some(item => {
      if (item.begin <= wakeUpCount && wakeUpCount < item.end) {
        wakeupScore = item.score;
        return true;
      }
    })

    deep_standards.some(item => {
      if (item.begin <= depthPercent && depthPercent < item.end) {
        depthScore = item.score;
        return true;
      }
    })

    let score = sleepLengthScore * rate[0] + sleepStartScore * rate[1] + wakeupScore * rate[2] + depthScore * rate[3];
    return score;
  },
  //计算心率得分
  calcHeartScore(heartRate) {
    let score = 0;
    if (heartRate == 0) return score;

    heartRate_standards.some(item => {
      if (item.begin <= heartRate && heartRate < item.end) {
        score = item.score;
        return true;
      }
    })

    return score;
  },
  //计算步数得分
  calcStepScore(stepNum) {
    let score = 0;
    if (stepNum == 0) return score;

    let step_standards;
    if (this.data.age < 13 && this.data.age >= 6) {
      step_standards = step_standards_child;
    } else if (this.data.age < 17 && this.data.age >= 14) {
      step_standards = step_standards_young;
    } else {
      step_standards = step_standards_adult;
    }

    step_standards.some(item => {
      if (item.begin <= stepNum && stepNum < item.end) {
        score = item.score;
        return true;
      }
    })

    return score;
  },
  //计算体质健康指数
  calcHealthScore(testScore, sleepScore, heartRateScore, setpScore) {
    let healthScore = 0;
    if (testScore == 0) {
      healthScore = (sleepScore * 0.35 + heartRateScore * 0.15 + setpScore * 0.15) / 0.65;
      healthScore = Math.round(healthScore);
    } else {
      healthScore = testScore * 0.35 + sleepScore * 0.35 + heartRateScore * 0.15 + setpScore * 0.15;
      healthScore = Math.round(healthScore);
    }

    return healthScore;
  },
  //获取手环电量
  getVoltage() {
    let that = this;
    app.api.ajaxSubmit("/node/wx/home/getVoltage", {
      deviceNum: wx.getStorageSync("deviceNum"),
      date: that.data.now
    }).then(response => {
      let info = response.data.data;
      if (response.data.error == 10000 && info.length) {
        let voltage = info[info.length - 1].voltage;
        let elec;
        if (voltage >= 3.8) {
          elec = "正常";
        } else if (voltage >= 3.6) {
          elec = "偏低";
        } else {
          elec = "过低";
        }

        this.setData({
          elec: elec
        })
      }
    }).catch(err => {
      wx.showToast({
        title: '服务器开小差',
        icon: "none",
        duration: 2000
      })
    })
  }
})